<?php

/**
 * product actions.
 *
 * @package    sf_sandbox
 * @subpackage product
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class productActions extends sfActions
{
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
        // remove sort and filters
        $this->getUser()->getAttributeHolder()->removeNamespace('product');
        $this->getUser()->getAttributeHolder()->removeNamespace('product/filters');

        return $this->forward('product', 'list');
    }

    public function executeList()
    {
        //$this->forward('product', 'category');

        $this->processFilters();
        $this->filters = $this->getUser()->getAttributeHolder()->getAll('product/filters');

        $c = new Criteria();
        $this->addFiltersCriteria($c);
        $c->add(ProductPeer::STATUS_ID, MyConstants::STATUS_APPROVED);

        $this->categorySelected = null;
        if( ($treeId = (int)$this->getRequestParameter('id', 0)) > 0 )
        {
            /* @var $tree Tree */
            $tree = TreePeer::retrieveByPK($treeId);
            $this->forward404Unless($tree);
            if($tree->getLabel() == 'PRODUCTS')
            {
//                $main = Tree::getTreeByLabel('PRODUCTS', sfContext::getInstance()->getUser()->getCulture());
//                if( $main[0]['children'][0]['obj'] )
//                {
//                    if($main[0]['children'][0]['children'][0]['obj'])
//                    {
//                        $child = $main[0]['children'][0]['children'][0]['obj']->getId();
//                        $this->redirect('tree/page?id=' . $child);
//                    }else 
//                    {
//                        $child = $main[0]['children'][0]['obj']->getId();
//                        $this->redirect('tree/page?id=' . $child);
//                    }
//                }
                $c->add(ProductPeer::TAGS, ProductPeer::TAGS . ' REGEXP "[[:<:]]' . Product::NEW_TAG . '[[:>:]]"', Criteria::CUSTOM);
            }else
            {
                $parent = TreePeer::retrieveByPK($tree->getParentId());
                if($parent->getLabel() == 'PRODUCTS')
                {
                    $main = Tree::getTree($treeId, sfContext::getInstance()->getUser()->getCulture());
                    if(!empty($main[0]['children'][0]))
                    {
                        $child = $main[0]['children'][0]['obj']->getId();
                        $this->redirect('tree/page?id=' . $child);
                    }
                }
                $c->add(ProductPeer::CATEGORY_ID, $tree->getObjId());
                $this->categorySelected = Category::getOrCreate($tree->getObjId());
            }
        }else 
        {
            $c->add(ProductPeer::TAGS, ProductPeer::TAGS . ' REGEXP "[[:<:]]' . Product::NEW_TAG . '[[:>:]]"', Criteria::CUSTOM);
        }

        $pager = new sfPropelPager('Product', 20);
        $pager->setCriteria($c);
        $pager->setPage($this->getRequestParameter('p', 1));
        $pager->init();

        $this->pager = $pager;
    }

    /**
     * Adds keywords to search criteria
     *
     * @param Criteria $c
     */
    protected function addFiltersCriteria($c)
    {
//        debugvar($this->filters, 'Filters to search:');
        
        /* @var $criterion Criterion */
        if( isset($this->filters['kwd']) )
        {
//            $cI18n = new Criteria();
            $criterion = $c->getNewCriterion(ProductI18nPeer::NAME, '%' . strip_tags($this->filters['kwd']) . '%', Criteria::LIKE );
            $criterion->addOr($c->getNewCriterion(ProductI18nPeer::TEXT, '%' . strip_tags($this->filters['kwd']) . '%', Criteria::LIKE ));
            $c->add($criterion);
            
            $c->add(ProductI18nPeer::CULTURE, $this->getUser()->getCulture());
            $c->addJoin(ProductPeer::ID, ProductI18nPeer::ID);
        }
        
        //debugvar($this->filters, 'Filter to apply:');
        if (isset($this->filters['id']))
        {
            $c->add(ProductPeer::CATEGORY_ID, $this->filters['id']);
        }
        if (isset($this->filters['price_from']) && $this->filters['price_from'] !== '')
        {
            $c->add(ProductPeer::PRICE, $this->filters['price_from'], Criteria::GREATER_THAN);
        }
        if (isset($this->filters['price_to']) && $this->filters['price_to'] !== '')
        {
            $c->add(ProductPeer::PRICE, $this->filters['price_to'], Criteria::LESS_THAN);
        }
        if (isset($this->filters['code']) && $this->filters['code'] !== '')
        {
            $c->add(ProductPeer::CODE, $this->filters['code']);
        }
    }


    protected function addSortCriteria($c)
    {
        if ($sort_column = $this->getUser()->getAttribute('sort', null, 'product/sort'))
        {
            $sort_column = ProductPeer::translateFieldName($sort_column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
            if ($this->getUser()->getAttribute('type', null, 'product/sort') == 'asc')
            {
                $c->addAscendingOrderByColumn($sort_column);
            }
            else
            {
                $c->addDescendingOrderByColumn($sort_column);
            }
        }
    }


    public function executeShow()
    {
        //$this->forward('default', 'module');

        $this->product = ProductPeer::retrieveByPk($this->getRequestParameter('id'));
    }


    /**
     * return search result
     *
     * @param string $search
     * @return object
     */
    public function executeSearch()
    {
        //debugvar($this->getRequestParameter('search'), 'parameters from form');

        $this->arSearchCategory = Product::getSearchCategory($this->getRequestParameter('search'));
        $this->arSearchProduct = Product::getSearchProduct($this->getRequestParameter('search'));
        //debugvar($arObjects, 'search - arObjects');

        $this->search = $this->getRequestParameter('search');
        $this->count_result = count($this->arSearchProduct);
    }


    /**
     * Ajax action which adds specified ID to list of user objcet to look
     */
    public function executeAddtolist()
    {
        // Get IDs of items to compare
        $arMyListIds = $this->getUser()->getAttribute('arMyList', array());
        //debugvar($arMyListIds, 'My list:');
        $objId = (int)$this->getRequestParameter('id');
        $this->product = ProductPeer::retrieveByPk($objId);
        $this->forward404Unless($this->product);
        if($objId > 0)
        {
            if(empty($arMyListIds[$objId]))
            {
                $arMyListIds[$objId] = $objId;
                $this->product = ProductPeer::retrieveByPk($objId);
            }
            $this->getUser()->setAttribute('arMyList', $arMyListIds);
        }
    }

    public function executeRemovefromlist()
    {
        // Get IDs of items to compare
        $arMyListIds = $this->getUser()->getAttribute('arMyList', array());
        // debugvar($arMyListIds);
        $objId = (int)$this->getRequestParameter('id');
        if($objId > 0)
        {
            unset($arMyListIds[$objId]);
            // debugvar($arMyListIds);
            $this->getUser()->setAttribute('arMyList', $arMyListIds);
            $this->product = ProductPeer::retrieveByPk($objId);
        }
        // exit('redirecting...');
        if( !$this->getRequestParameter('redir') )
        {
            return $this->redirect('product/watchlist');
        }
    }

    public function executeClearwatchlist()
    {
        // Empty user selected items
        $this->getUser()->setAttribute('arMyList', array());
        $this->redirect('product/watchlist');
    }
     
    public function executeWatchlist()
    {
        $userId = get_user_id();
        //$this->user = User::getById($userId);
        //$this->forwardUnless($this->user->getId(), 'user', 'dologin');
        // Get IDs of items to compare
        $arMyListIds = $this->getUser()->getAttribute('arMyList', array());

        $this->arMyList = null;
        if(count($arMyListIds) > 0)
        {
            $c = new Criteria();
            $c->add(ProductPeer::ID, $arMyListIds, Criteria::IN);
            $this->arMyList = ProductPeer::doSelect($c);
            //debugvar($this->arMyList);
        }
         
        $this->categories = Category::getBranchById($this->getRequestParameter('id'));
        //debugvar($this->categories, 'categories');
        if( count($this->categories) )
        {
            $this->categoryLast = $this->categories[count($this->categories)-1]['name'];
        }
        else
        {
            $this->categoryLast = '';
        }
        $this->categoryId = $this->getRequestParameter('id');

    }

    protected function processFilters()
    {
        if ($this->getRequest()->hasParameter('filter'))
        {
            $filters = $this->getRequestParameter('filters', array());

            $this->getUser()->getAttributeHolder()->removeNamespace('product');
            $this->getUser()->getAttributeHolder()->removeNamespace('product/filters');
            $this->getUser()->getAttributeHolder()->add($filters, 'product/filters');
        }

//        debugvar($filters,'filters');
    }

    protected function processSort()
    {
        if ($this->getRequestParameter('sort'))
        {
            $this->getUser()->setAttribute('sort', $this->getRequestParameter('sort'), 'product/sort');
            $this->getUser()->setAttribute('type', $this->getRequestParameter('type', 'asc'), 'product/sort');
        }

        if (!$this->getUser()->getAttribute('sort', null, 'product/sort'))
        {
            $this->getUser()->setAttribute('sort', 'priority', 'product/sort');
            $this->getUser()->setAttribute('type', 'asc', 'product/sort');
        }
    }


    /**
     * return new products result
     *
     * @return object
     */
    public function executeNew()
    {
        $this->products = Product::getByTag(PRODUCT::NEW_TAG);
        $this->categorySelected = null;

        $this->pager = new sfPropelPager('Product');
        $this->setTemplate('list');
    }

    /**
     * return promotion products result
     *
     * @return object
     */
    public function executeSales()
    {
        $this->products = Product::getByTag(PRODUCT::PROMO_TAG);
        $this->categorySelected = null;

        $this->pager = new sfPropelPager('Product');
        $this->setTemplate('list');
    }


}